package com.boglond.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;


public class XmlUtil {
    private static final Logger log = LoggerFactory.getLogger(XmlUtil.class);

    private static final String PROJECT_SAVE_PATH = PropertyUtil.getValueByKey("project.save.path");

    private static final String DAO_XML_SAVE_PATH = new StringBuffer().append(PROJECT_SAVE_PATH).
            append(PropertyUtil.getValueByKey("dao.xml.save.path")).toString();

    public static boolean createBasicTableXmlMapperFile(String xmlFileName,String namespace){
        //创建一个xml文档
        Document doc = DocumentHelper.createDocument();
        doc.addDocType("mapper","-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd",null);
        //向xml文件中添加注释
        doc.addComment("这是mapper xml 文件");
        Element root = doc.addElement("mapper");
        root.addAttribute("namespace",namespace);
        //用于格式化xml内容和设置头部标签
        OutputFormat format = OutputFormat.createPrettyPrint();
        //设置xml文档的编码为utf-8
        format.setEncoding("utf-8");

        Writer out;
        XMLWriter writer = null;
        try {
            File filePath = new File(DAO_XML_SAVE_PATH);
            if(!filePath.exists()){
                filePath.mkdirs();
            }
            String fileName = xmlFileName + ".xml";
            File docFile = new File(filePath,fileName);
            //创建一个输出流对象
            out = new FileWriter(docFile);
            //创建一个dom4j创建xml的对象
            writer = new XMLWriter(out, format);
            //调用write方法将doc文档写到指定路径
            writer.write(doc);
            log.info(">> XmlUtil 生成:{} 初始化XML文件成功",xmlFileName);
        } catch (IOException e) {
            log.error(">> XmlUtil 生成:{} 初始化XML文件异常,详细信息:{}",xmlFileName,e);
            return false;
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
    public static Document xmlConvertDocument(String xmlFileName) {
        Document document = null;
        SAXReader reader = new SAXReader();
        try {
            document = reader.read(new File(DAO_XML_SAVE_PATH + xmlFileName + ".xml"));
        } catch (DocumentException e) {
            log.error(">> XmlUtil 把xml文件:{},转换成Document对象异常,详细信息:{}",xmlFileName,e);
        }
        return document;
    }

    public static boolean documentConvertXml(Document document,String xmlFileName) {
        //用于格式化xml内容和设置头部标签
        OutputFormat format = OutputFormat.createPrettyPrint();
        //设置xml文档的编码为utf-8
        format.setEncoding("utf-8");
        Writer out;
        XMLWriter writer = null;
        try {
            //创建一个输出流对象
            out = new FileWriter(DAO_XML_SAVE_PATH + xmlFileName + ".xml");
            //创建一个dom4j创建xml的对象
            writer = new XMLWriter(out, format);
            //调用write方法将doc文档写到指定路径
            writer.write(document);
            log.info(">> XmlUtil 生成:{} XML文件成功",xmlFileName);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(">> XmlUtil 生成:{} XML文件异常，详细信息:{}",xmlFileName,e);
            return false;
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }
    public static void testCreateXml() {
        //创建一个xml文档
        Document doc = DocumentHelper.createDocument();
        //向xml文件中添加注释
        doc.addComment("这里是注释");
        //创建一个名为mapper的节点，因为是第一个创建，所以是根节点,再通过doc创建一个则会报错。
        Element root = doc.addElement("mapper");
        //在root节点下创建一个名为sql的节点
        Element sql = root.addElement("sql");
        //给student节点添加属性
        sql.addAttribute("id", "Base_Column_List");

        //设置子节点的文本
        sql.setText("book_resource_id, book_id, resource_url, type");
        //用于格式化xml内容和设置头部标签
        OutputFormat format = OutputFormat.createPrettyPrint();
        //设置xml文档的编码为utf-8
        format.setEncoding("utf-8");
        Writer out;
        try {
            //创建一个输出流对象
            out = new FileWriter("/Users/boglond/IdeaProjects/code-printer/src/main/resources/TestDAO.xml");
            //创建一个dom4j创建xml的对象
            XMLWriter writer = new XMLWriter(out, format);
            //调用write方法将doc文档写到指定路径
            writer.write(doc);
            writer.close();
            System.out.print("生成XML文件成功");
        } catch (IOException e) {
            System.out.print("生成XML文件失败");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testCreateXml();
    }


}
